﻿<html>
<head>
</head>
<body>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
var oauth=ChromeExOAuth.initBackgroundPage({
	'request_url': "http://api.t.sina.com.cn/oauth/request_token",
	'authorize_url': "http://api.t.sina.com.cn/oauth/authorize",
	'access_url': "http://api.t.sina.com.cn/oauth/access_token",
	'consumer_key':"3640942651",
	'consumer_secret': "2d5ce5527431c7ee3670f94de918d248",
	'scope':'',
	'app_name': "我的新浪微博"
});	

var defaultOptions = "{\"hide\":false,\"draft\":false, \"bigPic\":false, \"nolimit\":false, \"ad\": false, \"sendToSina\": false, shortcut:false}";
var defaultHide = "{\"admin\":{\"right\":[]}, \"profile\":{\"right\":[]}}";

if(getLocalStorageVal('options', '') == '')
{
  localStorage['options'] = defaultOptions;
}

if(getLocalStorageVal('hide', '') == '')
{
  localStorage['hide'] = defaultHide;
}
    chrome.extension.onRequest.addListener(onRequest);
    function onRequest(request, sender, callback) {
        switch(request.action)
        {
            case 'publish':
                var remaining = request.text;

                for(var n ='', adjust = 0, len=0, ss='', timeout=1000;;)
                {
                    n = Core.String.subStr(remaining, len + adjust , 260);
                    ss=n.replace(/\*/g," ").replace(/[^\x00-\xff]/g,"**");
                    len+=ss.length;
                    adjust ++;
                    
                    if(ss.length == 0)
                    {
                        break;
                    }
                    
                    sendStatus(n);
                }
                
                callback('finished');
            break;
            case "getOptions":
                var opt = {'options':JSON.parse(getLocalStorageVal("options")), 'hide':JSON.parse(getLocalStorageVal("hide"))};
                callback(opt);
                break;
            case "hide":
                var ele = request.ele;
                var hide = JSON.parse(getLocalStorageVal("hide"));
                switch(ele.pos)
                {
                    case 'right':
                        if(ele.admin)
                        {
                            hide.admin.right = $.merge(hide.admin.right, [ele.index]);
                        }
                        else
                        {
                            hide.profile.right = $.merge(hide.profile.right, [ele.index]);
                        }
                        break;
                }
                localStorage['hide'] = JSON.stringify(hide);
                callback(JSON.stringify(hide));
                break;
            case "getDraft":
                var draftUrl = chrome.extension.getURL("draft.txt");
                $.get(draftUrl, function(data)
                {
                    callback(data);
                });
                break;
            case "getDraftData":
                var wData = getLocalStorageVal("weiboDraftData", "[]");
                    var draftData = JSON.parse(wData);
                    var draftLi = "<ol class=\"lv_textlist\" id=\"draftData\">";
                    if(draftData.length > 0)
                    {
                        $.each(draftData, function(index, val)
                        {
                            if(index >= 10)
                            {
                                return false;
                            }
                            if(val.text.length > 0)
                            {
                                var text = val.text;
                                var datetime = val.time;
                                var draftIndex = val.index;
                                var liId = "draftLi" + draftIndex;
                                var checked = index == 0 ? "checked='checked'" : "";
                                var li = "<li index='" + draftIndex + "'><input id='" + liId + "' name=\"v_draft\" type=\"radio\"" + checked + "><label for='" +liId +"'>" + text +"</label><a class='close' style=\"display:none\" href=\"javascript:void(0);\">删除</a></li>"
                                draftLi += li;
                            }
                        });
                    }
                    else
                    {
                        draftLi += "目前你还没有草稿，点上面的按钮即可保存，不信试试<img src='http://timg.sjs.sinajs.cn/t3/style/images/common/face/ext/normal/bc/otm_org.gif'/>";
                    }
                    draftLi += "</ol>";
                    
                    
                    callback({data:draftLi, count:draftData.length});
                break;
            case "saveDraft":
                var dd = getLocalStorageVal("weiboDraftData", "[]");
                var draftData = JSON.parse(dd);
                var index = parseInt( getLocalStorageVal("latestDraftId", 0)) + 1;
                var data = {text:request.text, time:request.time, index:index};
                draftData.splice(0,0,data);
                localStorage["weiboDraftData"] = JSON.stringify(draftData);
                localStorage["latestDraftId"] = index;
                
                callback({time : request.time,index : index});
                break;
            case "deleteDraft":
                var index = request.index;
                var draftData = JSON.parse(getLocalStorageVal("weiboDraftData", "[]"));
                if(draftData.length > 0 && index)
                {
                    $.each(draftData, function(i)
                    {
                        if(draftData[i].index == index)
                        {
                            draftData.splice(i, 1);
                            return false;
                        }
                    });
                    
                    localStorage["weiboDraftData"] = JSON.stringify(draftData);
                }
                
                
                callback('success');
                break;
            case "getPos":
                $.get(request.geoUrl, function(data)
                {
                    callback(data);
                });
                break;
        }
    }
    
        if(JSON.parse(getLocalStorageVal('options', defaultOptions)).sendToSina === true)
        {
            chrome.contextMenus.create({"title": "\"i新浪微博\"分享", "contexts":["page","selection"], "onclick": createShadowbox});
        }
        
        function createShadowbox(info, tab) {
            chrome.tabs.getSelected(null, function(tab) {
                    
                    chrome.tabs.executeScript(tab.id, {file: "commonmyweibo.js"});
            });
                    
            chrome.tabs.getSelected(null, function(tab) {
            });
        }
        
        function getLocalStorageVal(key, defaultVal) {
        
        var val = window.localStorage[key];
        if (val == undefined || val == null) {
            return defaultVal;
        } else {
            return val;
        }
    };
    
            function sendStatus(status) {
              var url = 'http://api.t.sina.com.cn/statuses/update.json';
              var encode_status=encodeURIComponent(status);
              var request = {
                        'method': 'post',
                        'parameters':{
		                    'status':encode_status
	                        }
				        };
                if(!oauth.hasToken()){
                    var conf=confirm("授权给\"i新浪微博\"Chrome插件?");
                    if(conf)
                    {
					    oauth.authorize(function(){
				            oauth.sendSignedRequest(url, onSentStatus, request);
				            });          
				     }
				}
				else
				{
				      oauth.sendSignedRequest(url, onSentStatus, request);
				}

      };
      
      function onSentStatus(response)
      {

      }
</script>

</body>
</html>
